package com.yzw.endecoderfixed;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * @Author: YangZhenWei
 * @PROJECT_NAME: nettyTeach
 * @DESCRIPTION: 服务端启动类
 * @USER: root
 * @DATE: 2023/2/8 22:51
 **/
public class AppServerEnDecoder {

    private final int port;

    public AppServerEnDecoder(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        // 负责接收客户端的链接
        EventLoopGroup bossGroup = new NioEventLoopGroup();// io线程池
        // 负责处理消息传输
        EventLoopGroup workGroup = new NioEventLoopGroup();// io线程池
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class) // 实例化一个通道
                    .localAddress(new InetSocketAddress(port)) // 指定远程的ip和端口
                    .option(ChannelOption.SO_BACKLOG,128)// 最大链接数128 option主要针对boss线程租
                    .childOption(ChannelOption.SO_KEEPALIVE,true)// 启用心跳检测机制 childOption主要针对work线程租
                    .childHandler(new InitializerServerEnDeCoder());
            //链接获取异步操作的结果值，链接到远程节点，等待链接完成
            ChannelFuture channelFuture = b.bind().sync();
            System.out.println("在"+channelFuture.channel().localAddress()+"监听");

            // 阻塞操作，closeFuture()开启了一个Channel的监听器,这期间channel在进行各种操作
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully().sync();
            workGroup.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws Exception {
        new AppServerEnDecoder(18080).run();
    }
}
